package com.sskj.finance.ui.activity;


import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.StaticScheme;
import com.github.yoojia.inputs.WidgetAccess;
import com.jakewharton.rxbinding2.widget.RxSearchView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.sskj.common.base.App;
import com.sskj.common.util.ClickUtil;
import com.sskj.finance.R;
import com.sskj.finance.R2;
import com.sskj.finance.bean.HomeBorrowBorrowInfoBean;
import com.sskj.finance.bean.HomeBorrowMortgageInfoBean;
import com.sskj.finance.bean.HomeQbwCoinsList;
import com.sskj.finance.presenter.BorrowActivityPresenter;
import com.sskj.finance.util.TipFinanUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.util.BottomSheetUtil;
import com.sskj.lib.util.CoinUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

@Route(path = RConfig.FINAN_BORROW)//借款/借币
public class BorrowActivity extends BaseActivity<BorrowActivityPresenter> {
    @Autowired
    boolean isBorrowCoin;
    @BindView(R2.id.tvMortgageCoin)
    TextView tvMortgageCoin;
    @BindView(R2.id.tvAvailable)
    TextView tvAvailable;
    @BindView(R2.id.tvMortgageUnit)
    TextView tvMortgageUnit;
    @BindView(R2.id.tvRMB)
    TextView tvRMB;
    @BindView(R2.id.etNumMortgage)
    EditText etNumMortgage;
    @BindView(R2.id.tvMortgageUnit2)
    TextView tvMortgageUnit2;
    @BindView(R2.id.tvDay)
    TextView tvDay;
    @BindView(R2.id.tvRate)
    TextView tvRate;
    @BindView(R2.id.tvBorrowCoin)
    TextView tvBorrowCoin;
    @BindView(R2.id.tvBorrowMostNum)
    TextView tvBorrowMostNum;
    @BindView(R2.id.tvBorrowCoinUnit)
    TextView tvBorrowCoinUnit;
    @BindView(R2.id.etNumBorrow)
    EditText etNumBorrow;
    @BindView(R2.id.tvBorrowCoinUnit2)
    TextView tvBorrowCoinUnit2;
    @BindView(R2.id.btSubmit)
    Button btSubmit;
    @BindView(R2.id.tvAllRecord)
    TextView tvAllRecord;
    @BindView(R2.id.frameLayout)
    FrameLayout frameLayout;
    private String type;
    private List<HomeQbwCoinsList> mortgageCoinsLists;
    private HomeQbwCoinsList coinBean;
    private HomeBorrowMortgageInfoBean mortgageCoin;//迪亚比重
    private BottomSheetDialog bottomSheetDay;
    private HomeQbwCoinsList borrowBean;
    private List<HomeQbwCoinsList> borrowCoinsLists;
    private BottomSheetDialog bottomSheetBorrowCoin;
    private BottomSheetDialog bottomSheetMortgageCoin;
    private List<String> days;
    private String day;
    private BottomSheetDialog bottomSheetDialogPwd;

    @Override
    protected int getLayoutId() {
        return R.layout.finan_activity_borrow;
    }

    @Override
    public BorrowActivityPresenter getPresenter() {
        return new BorrowActivityPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        type = isBorrowCoin ? "2" : "1";
        setTitle(isBorrowCoin ? App.INSTANCE.getString(R.string.finan_borrowActivity1_j) : App.INSTANCE.getString(R.string.finan_borrowActivity2_j));
        setRightTitle(App.INSTANCE.getString(R.string.finan_borrowActivity3_j), v -> {
            ARouter.getInstance().build(RConfig.APP_GUIDE_WEB).withBoolean(Constans.IS_BORROW, true).navigation();
        });
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frameLayout, (Fragment) ARouter.getInstance().build(RConfig.FINAN_FRAGMENT_DYJK)
                        .withString(Constans.TYPE, type)
                        .withString(Constans.STATUS, "1")
                        .navigation())
                .commit();
    }

    /**
     * 请求接口更改比例
     *
     * @param mortgageNum
     */
    private void changeRate(String mortgageNum) {
        if (TextUtils.isEmpty(mortgageNum) ||
                TextUtils.isEmpty(mortgageNum) ||
                Double.valueOf(mortgageNum) == 0) {
            tvRate.setText("");
            tvBorrowMostNum.setText("");
            return;
        }
        mPresenter.homeBorrowBorrowInfo(type, mortgageCoin.getPname(), borrowBean.getMark(), mortgageNum, day);
    }

    @Override
    protected void initData() {
        mPresenter.homeQbwCoinsListUp(type);
        mPresenter.getMorgageDay();

    }

    @Override
    protected void initEvent() {
        ClickUtil.click(tvAllRecord, () -> {
            ARouter.getInstance().build(RConfig.FINAN_MORTGAGE_RECORD).navigation();
        });
        ClickUtil.click(tvDay, () -> {
            if (days == null) {
                mPresenter.getMorgageDay();
                return;
            }
            Flowable.fromIterable(days)
                    .map(item -> item + App.INSTANCE.getString(R.string.finan_borrowActivity4_j))
                    .toList()
                    .subscribe((strings, throwable) -> {
                        if (bottomSheetDay == null) {
                            bottomSheetDay = BottomSheetUtil.getBottomSheet(this, null, (recyclerView, i, view) -> {
                                bottomSheetDay.dismiss();
                                tvDay.setText(days.get(i) + App.INSTANCE.getString(R.string.finan_borrowActivity4_j));
                                changeRate(etNumMortgage.getText().toString());
                            }, strings);
                        }
                        bottomSheetDay.show();
                    });
        });
        RxTextView.textChanges(etNumMortgage)
                .debounce(1, TimeUnit.SECONDS).skip(1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(charSequence -> {
                    String mortgageNum = charSequence.toString();
                    changeRate(mortgageNum);

                });
        ClickUtil.click(tvMortgageCoin, () -> {
            if (bottomSheetMortgageCoin == null) {
                mPresenter.homeQbwCoinsListUp(type);
                return;
            }
            bottomSheetMortgageCoin.show();
        });
        ClickUtil.click(tvBorrowCoin, () -> {
            if (bottomSheetBorrowCoin == null) {
                mPresenter.homeQbwCoinsListUp(type);
                return;
            }
            bottomSheetBorrowCoin.show();
        });
        AndroidNextInputs inputs = new AndroidNextInputs();
        WidgetAccess widgetAccess = new WidgetAccess(this);
        inputs
                .add(widgetAccess.findEditText(R.id.etNumMortgage), StaticScheme.NotBlank())
                .add(widgetAccess.findEditText(R.id.etNumBorrow), StaticScheme.NotBlank());
        ClickUtil.click(btSubmit, () -> {
            if (inputs.test()) {

                bottomSheetDialogPwd = BottomSheetUtil.showPwd(this, str -> {
                    bottomSheetDialogPwd.dismiss();
                    mPresenter.homeBorrowBorrowAdd(type, mortgageCoin.getPname(),
                            borrowBean.getMark(), etNumMortgage.getText().toString(),
                            day, etNumBorrow.getText().toString(), str[0]);
                });
                bottomSheetDialogPwd.show();

            }
        });
    }

    private void changeCoin() {
        etNumMortgage.setText("");
        tvBorrowMostNum.setText("");
        tvMortgageCoin.setText(coinBean.getMark());
        tvMortgageUnit.setText(coinBean.getMark());
        tvMortgageUnit2.setText(coinBean.getMark());
        mPresenter.homeBorrowMortgageInfo(type, coinBean.getMark());
    }

    private void changeBorrowCoin() {
        tvBorrowMostNum.setText("");
        etNumMortgage.setText("");
        tvBorrowCoin.setText(borrowBean.getMark());
        tvBorrowCoinUnit.setText(borrowBean.getMark());
        tvBorrowCoinUnit2.setText(borrowBean.getMark());
    }


    public void changeMortgageCoin(HomeBorrowMortgageInfoBean data) {
        mortgageCoin = data;
        tvAvailable.setText(CoinUtil.keepCoinNumMax(mortgageCoin.getPname(), mortgageCoin.getUsable()));
        tvRMB.setText(mortgageCoin.getPrice_cny());
        updateBorrowCoin(data.getIn_coins());
    }

    /**
     * 更新抵押币种可选择列表
     *
     * @param data
     */
    public void updateBorrowCoin(List<HomeQbwCoinsList> data) {
        borrowCoinsLists = data;
        if (borrowCoinsLists != null && borrowCoinsLists.size() > 0) {
            borrowBean = borrowCoinsLists.get(0);
            changeBorrowCoin();
            Flowable.fromIterable(borrowCoinsLists)
                    .map(item -> item.getMark())
                    .toList()
                    .subscribe((strings, throwable) -> {
                        bottomSheetBorrowCoin = BottomSheetUtil.getBottomSheet(BorrowActivity.this, null, (recyclerView, i, view) -> {
                            bottomSheetBorrowCoin.dismiss();
                            borrowBean = borrowCoinsLists.get(i);
                            changeBorrowCoin();
                        }, strings);
                    });

        }


    }

    /**
     * 更新抵押币种可选择列表
     *
     * @param data
     */
    public void updateMortgageCoin(List<HomeQbwCoinsList> data) {
        mortgageCoinsLists = data;
        if (mortgageCoinsLists != null && mortgageCoinsLists.size() > 0) {
            coinBean = mortgageCoinsLists.get(0);
            changeCoin();
            Flowable.fromIterable(mortgageCoinsLists)
                    .map(item -> item.getMark())
                    .toList()
                    .subscribe((strings, throwable) -> {
                        bottomSheetMortgageCoin = BottomSheetUtil.getBottomSheet(BorrowActivity.this, null, (recyclerView, i, view) -> {
                            bottomSheetMortgageCoin.dismiss();
                            coinBean = mortgageCoinsLists.get(i);
                            changeCoin();
                        }, strings);
                    });
        }
    }

    public void updateRate(HomeBorrowBorrowInfoBean data) {
        tvRate.setText(String.format(App.INSTANCE.getString(R.string.finan_borrowActivity5_j), data.getRate()));
        tvBorrowMostNum.setText(CoinUtil.keepCoinNumMax(data.getIn_code(), data.getIn_num()));
    }

    public void borrowSuccess() {
        etNumMortgage.setText("");
        etNumBorrow.setText("");
        LiveDataBus.get().with(RxBusCode.UPDATE_BORROW, Integer.class).postValue(1);
    }

    public void updateMorgageDay(List<String> data) {
        days = data;
        tvDay.setText(days.get(0) + App.INSTANCE.getString(R.string.finan_borrowActivity4_j));
        day = days.get(0);
    }
}
